package com.yuxl.admin.common.core.utils;

import cn.hutool.core.convert.Convert;
import jakarta.annotation.Resource;
import lombok.experimental.UtilityClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Range;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 缓存工具类
 */
@UtilityClass
public class RedisUtil {

	private static final Long SUCCESS = 1L;

	/**
	 * 指定缓存失效时间
	 * @param key 键
	 * @param time 时间(秒)
	 */
	public Mono<Boolean> expire(String key, long time) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.expire(key, Duration.ofSeconds(time)).thenReturn(true);
	}

	/**
	 * 根据 key 获取过期时间
	 * @param key 键 不能为null
	 * @return 时间(秒) 返回0代表为永久有效
	 */
	public Mono<Long> getExpire(Object key) {
		ReactiveRedisTemplate<Object, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.getExpire(key).map(Duration::getSeconds);
	}

	/**
	 * 判断key是否存在
	 * @param key 键
	 * @return true 存在 false不存在
	 */
	public Mono<Boolean> hasKey(String key) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.hasKey(key);
	}

	/**
	 * 删除缓存
	 * @param keys 可以传一个值 或多个
	 */
	public Mono<Void> del(String... keys) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return Flux.fromArray(keys)
				.flatMap(reactiveRedisTemplate::delete)
				.then();
	}

	/**
	 * 获取锁
	 * @param lockKey 锁key
	 * @param value value
	 * @param expireTime：单位-秒
	 * @return boolean
	 */
	public Mono<Boolean> getLock(String lockKey, String value, int expireTime) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForValue().setIfAbsent(lockKey, value, Duration.ofSeconds(expireTime));
	}

	/**
	 * 释放锁
	 * @param lockKey 锁key
	 * @param value value
	 * @return boolean
	 */
	public Flux<Boolean> releaseLock(String lockKey, String value) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) == 1 else return 0 end";
		RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
		return reactiveRedisTemplate.execute(redisScript, Collections.singletonList(lockKey), List.of(value)).map(k -> k == 1);
	}

	// ============================String=============================

	/**
	 * 普通缓存获取
	 * @param key 键
	 * @return 值
	 */
	public <T> Mono<T> get(String key) {
		ReactiveRedisTemplate<String, T> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForValue().get(key);
	}

	/**
	 * 批量获取
	 * @param keys
	 * @return
	 */
	public <T> Flux<T> multiGet(List<String> keys) {
		ReactiveRedisTemplate<String, T> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForValue().multiGet(keys).flatMapIterable(list -> list);
	}

	/**
	 * 普通缓存放入
	 * @param key 键
	 * @param value 值
	 * @return true成功 false失败
	 */
	public Mono<Boolean> set(String key, Object value) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForValue().set(key, value).thenReturn(true);
	}

	/**
	 * 普通缓存放入并设置时间
	 * @param key 键
	 * @param value 值
	 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
	 * @return true成功 false 失败
	 */
	public Mono<Boolean> set(String key, Object value, long time) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		ReactiveValueOperations<String, Object> ops = reactiveRedisTemplate.opsForValue();
		if (time > 0) {
			return ops.set(key, value, Duration.ofSeconds(time)).thenReturn(true);
		} else {
			return ops.set(key, value).thenReturn(true);
		}
	}

	/**
	 * 普通缓存放入并设置时间
	 * @param key 键
	 * @param value 值
	 * @return true成功 false 失败
	 */
	public <T> Mono<Boolean> set(String key, T value, Duration duration) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		ReactiveValueOperations<String, Object> ops = reactiveRedisTemplate.opsForValue();
		if (duration.getSeconds() > 0) {
			return ops.set(key, value, duration).thenReturn(true);
		} else {
			return ops.set(key, value).thenReturn(true);
		}
	}

	// ================================Map=================================

	/**
	 * HashGet
	 * @param key 键 不能为null
	 * @param hashKey 项 不能为null
	 * @return 值
	 */
	public <HK, HV> Mono<HV> hget(String key, HK hashKey) {
		ReactiveRedisTemplate<String, HK> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.<HK, HV>opsForHash().get(key, hashKey);
	}

	/**
	 * 获取hashKey对应的所有键值
	 * @param key 键
	 * @return 对应的多个键值
	 */
	public <HK, HV> Flux<Map.Entry<HK, HV>> hmget(String key) {
		ReactiveRedisTemplate<String, HK> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.<HK, HV>opsForHash().entries(key);
	}

	/**
	 * HashSet
	 * @param key 键
	 * @param map 对应多个键值
	 * @return true 成功 false 失败
	 */
	public Mono<Void> hmset(String key, Map<String, Object> map) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForHash().putAll(key, map).then();
	}

	/**
	 * HashSet 并设置时间
	 * @param key 键
	 * @param map 对应多个键值
	 * @param time 时间(秒)
	 * @return true成功 false失败
	 */
	public Mono<Boolean> hmset(String key, Map<String, Object> map, long time) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		ReactiveHashOperations<String, String, Object> hashOps = reactiveRedisTemplate.opsForHash();
		return hashOps.putAll(key, map)
				.then(reactiveRedisTemplate.expire(key, Duration.ofSeconds(time)));
	}

	/**
	 * 向一张hash表中放入数据,如果不存在将创建
	 * @param key 键
	 * @param item 项
	 * @param value 值
	 * @return true 成功 false失败
	 */
	public Mono<Boolean> hset(String key, String item, Object value) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		ReactiveHashOperations<String, String, Object> hashOps = reactiveRedisTemplate.opsForHash();
		return hashOps.put(key, item, value);
	}

	/**
	 * 向一张hash表中放入数据,如果不存在将创建
	 * @param key 键
	 * @param item 项
	 * @param value 值
	 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
	 * @return true 成功 false失败
	 */
	public Mono<Boolean> hset(String key, String item, Object value, long time) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		ReactiveHashOperations<String, String, Object> hashOps = reactiveRedisTemplate.opsForHash();
		return hashOps.put(key, item, value)
				.then(reactiveRedisTemplate.expire(key, Duration.ofSeconds(time)));
	}

	/**
	 * 删除hash表中的值
	 * @param key 键 不能为null
	 * @param items 项 可以使多个 不能为null
	 */
	public Mono<Long> hdel(String key, Object... items) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		ReactiveHashOperations<String, Object, Object> hashOps = reactiveRedisTemplate.opsForHash();
		return hashOps.remove(key, items);
	}

	/**
	 * 判断hash表中是否有该项的值
	 * @param key 键 不能为null
	 * @param item 项 不能为null
	 * @return true 存在 false不存在
	 */
	public Mono<Boolean> hHasKey(String key, Object item) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		ReactiveHashOperations<String, String, Object> hashOps = reactiveRedisTemplate.opsForHash();
		return hashOps.hasKey(key, item);
	}

	/**
	 * hash递增 如果不存在,就会创建一个 并把新增后的值返回
	 * @param key 键
	 * @param item 项
	 * @param by 要增加几(大于0)
	 * @return
	 */
	public Mono<Double> hincr(String key, String item, double by) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		ReactiveHashOperations<String, String, Double> hashOps = reactiveRedisTemplate.opsForHash();
		return hashOps.increment(key, item, by);
	}

	/**
	 * hash递减
	 * @param key 键
	 * @param item 项
	 * @param by 要减少记(小于0)
	 * @return
	 */
	public Mono<Double> hdecr(String key, String item, double by) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		ReactiveHashOperations<String, String, Double> hashOps = reactiveRedisTemplate.opsForHash();
		return hashOps.increment(key, item, -by);
	}

	// ============================set=============================

	/**
	 * 根据key获取Set中的所有值
	 * @param key 键
	 * @return
	 */
	public <T> Flux<T> sGet(String key) {
		ReactiveRedisTemplate<String, T> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForSet().members(key);
	}

	/**
	 * 根据value从一个set中查询,是否存在
	 * @param key 键
	 * @param value 值
	 * @return true 存在 false不存在
	 */
	public Mono<Boolean> sHasKey(String key, Object value) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForSet().isMember(key, value);
	}

	/**
	 * 将数据放入set缓存
	 * @param key 键
	 * @param values 值 可以是多个
	 * @return 成功个数
	 */
	public Mono<Long> sSet(String key, Object... values) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForSet().add(key, values);
	}

	/**
	 * 将set数据放入缓存
	 * @param key 键
	 * @param time 时间(秒)
	 * @param values 值 可以是多个
	 * @return 成功个数
	 */
	public Mono<Integer> sSetAndTime(String key, long time, Object... values) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForSet().add(key, values)
				.then(reactiveRedisTemplate.expire(key, Duration.ofSeconds(time)))
				.thenReturn(values.length);
	}

	/**
	 * 获取set缓存的长度
	 * @param key 键
	 * @return
	 */
	public Mono<Long> sGetSetSize(String key) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForSet().size(key);
	}

	/**
	 * 移除值为value的
	 * @param key 键
	 * @param values 值 可以是多个
	 * @return 移除的个数
	 */
	public Mono<Long> setRemove(String key, Object... values) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForSet().remove(key, values);
	}

	/**
	 * 获集合key1和集合key2的差集元素
	 * @param key 键
	 * @return
	 */
	public <T> Flux<T> sDifference(String key, String otherKey) {
		ReactiveRedisTemplate<String, T> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForSet().difference(key, otherKey);
	}

	// ===============================list=================================

	/**
	 * 获取list缓存的内容
	 * @param key 键
	 * @param start 开始
	 * @param end 结束 0 到 -1代表所有值
	 * @return
	 */
	public <T> Flux<T> lGet(String key, long start, long end) {
		ReactiveRedisTemplate<String, T> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForList().range(key, start, end);
	}

	/**
	 * 获取list缓存的长度
	 * @param key 键
	 * @return
	 */
	public Mono<Long> lGetListSize(String key) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForList().size(key);
	}

	/**
	 * 通过索引 获取list中的值
	 * @param key 键
	 * @param index 索引 index>=0时， 0 表头，1 第二个元素，依次类推；index<0时，-1，表尾，-2倒数第二个元素，依次类推
	 * @return
	 */
	public <T> Mono<T> lGetIndex(String key, long index) {
		ReactiveRedisTemplate<String, T> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForList().index(key, index);
	}

	/**
	 * 将list放入缓存
	 * @param key 键
	 * @param value 值
	 * @return
	 */
	public Mono<Long> lSet(String key, Object value) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForList().rightPush(key, value);
	}

	/**
	 * 将list放入缓存
	 * @param key 键
	 * @param value 值
	 * @param time 时间(秒)
	 * @return
	 */
	public Mono<Boolean> lSet(String key, Object value, long time) {
		ReactiveRedisTemplate<Object, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		reactiveRedisTemplate.opsForList().rightPush(key, value);
		if (time > 0) {
			return reactiveRedisTemplate.expire(key, Duration.ofSeconds(time));
		}
		return Mono.just(true);
	}

	/**
	 * 将list放入缓存
	 * @param key 键
	 * @param value 值
	 * @return
	 */
	public Mono<Long> lSet(String key, List<Object> value) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForList().rightPushAll(key, value);
	}

	/**
	 * 将list放入缓存
	 * @param key 键
	 * @param value 值
	 * @param time 时间(秒)
	 * @return
	 */
	public Mono<Boolean> lSet(String key, List<Object> value, long time) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		reactiveRedisTemplate.opsForList().rightPushAll(key, value);
		if (time > 0) {
			return expire(key, time);
		}
		return Mono.just(true);
	}

	/**
	 * 根据索引修改list中的某条数据
	 * @param key 键
	 * @param index 索引
	 * @param value 值
	 * @return /
	 */
	public Mono<Boolean> lUpdateIndex(String key, long index, Object value) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForList().set(key, index, value);
	}

	/**
	 * 移除N个值为value
	 * @param key 键
	 * @param count 移除多少个
	 * @param value 值
	 * @return 移除的个数
	 */
	public Mono<Long> lRemove(String key, long count, Object value) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForList().remove(key, count, value);
	}

	/**
	 * 将zSet数据放入缓存
	 * @param key
	 * @param time
	 * @param tuples
	 * @return
	 */
	public Mono<Long> zSetAndTime(String key, long time, Set<ZSetOperations.TypedTuple<Object>> tuples) {
		ReactiveRedisTemplate<String, Object> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		Mono<Long> count = reactiveRedisTemplate.opsForZSet().addAll(key, tuples);
		if (time > 0) {
			return expire(key, time).flatMap(k-> count);
		}
		return count;
	}

	/**
	 * Sorted set:有序集合获取
	 * @param key
	 * @param range
	 * @param limit
	 * @return
	 */
	public <T> Flux<T> zRangeByScore(String key, Range<Double> range, Limit limit) {
		ReactiveRedisTemplate<String, T> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForZSet().rangeByScore(key, range, limit);

	}

	/**
	 * Sorted set:有序集合获取 正序
	 * @param key
	 * @param range
	 * @return
	 */
	public <T> Flux<T> zRange(String key, Range<Long> range) {
		ReactiveRedisTemplate<String, T> reactiveRedisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return reactiveRedisTemplate.opsForZSet().range(key, range);

	}

	/**
	 * Sorted set:有序集合获取 倒叙
	 * @param key
	 * @param range
	 * @return
	 */
	public <T> Flux<T> zReverseRange(String key, Range<Long> range) {
		ReactiveRedisTemplate<String, T> redisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return redisTemplate.opsForZSet().reverseRange(key, range);

	}

	/**
	 * 获取zSet缓存的长度
	 * @param key 键
	 * @return
	 */
	public Mono<Long> zGetSetSize(String key) {
		ReactiveRedisTemplate<String, Object> redisTemplate = SpringContextHolder.getBean(ReactiveRedisTemplate.class);
		return redisTemplate.opsForZSet().size(key);
	}

}
